<template>
  <div class="right">
    <div class="mark-content-header">
      <span class="title">打分板</span>
      <a-button type="primary" danger @click="handelAllNoAnswer">
        {{ isAnswer ? '取消全选未作答' : '全选未作答' }}
      </a-button>
    </div>
    <div class="scllerView">
      <a-form ref="setForm" :model="currentTopic">
        <div class="score" v-for="(itesub, index) in currentTopic?.ckdaInfoList" :key="itesub.daId">
          <a-form-item
            :label="`${itesub.tmbh}:`"
            :name="['ckdaInfoList', index, 'setCkda']"
            :rules="{ required: true, message: '答案不能为空', trigger: 'change' }"
          >
            <a-checkbox-group
              :key="itesub.daId"
              v-model:value="itesub.setCkda"
              :options="itesub.radioLength"
              @change="handelChange($event, itesub)"
            />
          </a-form-item>
        </div>
        <label class="text-[15px] font-semibold">评阅备注</label>
        <a-form-item label="">
          <a-textarea v-model:value="currentTopic.pyBz" placeholder="评阅备注" />
        </a-form-item>
      </a-form>
    </div>
    <div class="submit truncate" @click="handleSubmit(false)">提交并评阅下一题</div>
    <div class="submit truncate" @click="handleSubmit(true)">提交并退出评阅</div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, h } from 'vue'

import { useTeacherMarkStore } from '/@/store/modules/teacherMark'
const teacherMarkStore = useTeacherMarkStore()
const currentTopic = computed(() => teacherMarkStore.getCurrentTopic ?? {})
const questionsInfo = computed(() => teacherMarkStore.getQuestions)
const pageLoading = computed(() => teacherMarkStore.getLoading)

import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const startTime: any = computed(() => userStore.getStartTime)
const addSubjectForm = computed(() => userStore.getSysConfig)

import { useRouter } from 'vue-router'
const router = useRouter()

import { useMessage } from '/@/hooks/web/useMessage'
const { createConfirm, createMessage } = useMessage()

import { throttle } from 'lodash-es'
import { submitKgtTopic, todoYcDftTopic } from '/@/api/teacher'
import dayjs from 'dayjs'

// 判断是否全部设置为未作答
const isAnswer = computed(() => {
  let arr = currentTopic.value?.ckdaInfoList
  for (let i = 0; i < arr?.length; i++) {
    if (!arr[i].setCkda?.includes('Z')) return false
  }
  return true
})
/**
 * 未作答方法
 */
function handelAllNoAnswer() {
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', `您确定${isAnswer.value ? '取消' : '设置'}全选未作答吗？`),
    onOk: async close3 => {
      let arr = currentTopic.value?.ckdaInfoList
      if (isAnswer.value) {
        for (let i = 0; i < arr.length; i++) {
          arr[i].setCkda.splice(0)
          arr[i].pyDa = ''
        }
      } else {
        for (let i = 0; i < arr.length; i++) {
          arr[i].setCkda = ['Z']
          arr[i].pyDa = 'Z'
        }
      }
      close3()
      await setForm.value.validate()
    },
  })
}

/**
 * 多选框校验
 * @param e
 * @param itesub
 */
function handelChange(e, arguent) {
  if (!arguent.pyDa && typeof arguent.pyDa !== 'boolean') arguent.pyDa = ''
  // if (currentTopic.value.tmlx == '多项选择题') {
  if (e.includes('Z') && !arguent.pyDa.includes('Z')) {
    arguent.setCkda = ['Z']
  } else if (e.includes('Z') && arguent.pyDa.includes('Z')) {
    arguent.setCkda.splice(arguent.setCkda.indexOf('Z'), 1)
  }
  // } else {
  //   //单选或者判断题
  //   if (e.length && (typeof arguent.pyDa === 'boolean' || arguent.pyDa.length)) {
  //     arguent.setCkda.splice(arguent.setCkda.indexOf(arguent.pyDa), 1)
  //   }
  // }

  arguent.pyDa = arguent.setCkda.join(',')
}

const setForm = ref()

let pyTpZs = 0 //评阅图片点击总数

// 是否校验图片全部点击查看
const isCheckImg = computed(() => {
  let imgLength = currentTopic.value.dtkqtxxVoList.length
  let clickTimes = 0
  pyTpZs = 0
  currentTopic.value.dtkqtxxVoList.forEach(ele => {
    if (ele.clickTimes) clickTimes += 1
    pyTpZs += ele.clickTimes || 0
  })
  return imgLength != clickTimes
})

// 提交试卷
const handleSubmit = throttle(
  async (isDropOut = false) => {
    if (!currentTopic.value.dtkqtxxVoList.length)
      return createMessage.error('当前试卷没有获取到图片,不能进行评阅提交')
    await setForm.value.validate()
    let durationNum = (+new Date() - +new Date(startTime.value)) / 1000 //当前试题评阅时长
    if (durationNum < addSubjectForm.value.pyLoadingSeconds)
      return createMessage.error(
        `请你在${Math.ceil(addSubjectForm.value.pyLoadingSeconds - durationNum)}秒后提交评阅结果`
      )
    if (
      addSubjectForm.value.clickDtkqtCheck4KgtFlag &&
      isCheckImg.value &&
      !questionsInfo.value.pyZycIdList //表示重评题
    )
      return createMessage.error('请对所有图片进行点击查看')
    if (pageLoading.value) return //防止多次提交
    teacherMarkStore.setLoading(true)
    let kgtSubmitList: any = []

    let arr = currentTopic.value?.ckdaInfoList
    for (let i = 0; i < arr.length; i++) {
      kgtSubmitList.push({
        pyDa: arr[i].pyDa,
        stId: arr[i].stId,
      })
    }

    try {
      let requrFun = submitKgtTopic
      if (questionsInfo.value.pyZycIdList) {
        requrFun = todoYcDftTopic
      }
      requrFun({
        pyZycId: questionsInfo.value.pyZycId || questionsInfo.value.pyZycIdList[0], //评阅资源池
        pyTpZs, //评阅图片总数
        pyKssj: startTime.value, //评阅开始时间
        pyTjsj: dayjs().format('YYYY-MM-DD HH:mm:ss'), //评阅提交时间
        pyBz: currentTopic.value.pyBz, //评阅备注
        fpFlag: questionsInfo.value.fpFlag, //是否为复评题
        kgtSubmitList,
      }).then(res => {
        if (res.code == 200) {
          createMessage.success('提交成功')
          // 是否退出阅卷
          if (isDropOut) {
            router.back()
            return
          }
          // 获取下一次试题试卷标识符
          teacherMarkStore.setNext(true)
        } else {
          createMessage.error(res.message)
        }
      })
    } finally {
      teacherMarkStore.setLoading(false)
    }
  },
  1000,
  {
    trailing: false,
  }
)
</script>

<style lang="less" scoped>
.right {
  flex: 1;
  background: #fff;
  border-radius: 5px;
  height: 100%;
  .mark-content-header {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    border-bottom: 2px solid #ddd;
    justify-content: space-between;
    .title {
      font-size: 16px;
      font-weight: 700;
      margin-right: 20px;
      color: #3e98e8;
    }
  }

  .scllerView {
    overflow-y: auto;
    height: calc(100% - 200px);
    padding: 20px;
    box-sizing: border-box;
  }

  .submit {
    cursor: pointer;
    color: white;
    background: #1d86fc;
    border-radius: 4px;
    margin: 20px 30px;
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
